<?php
defined('_JEXEC') or die('Restricted access');

require_once(JPATH_COMPONENT.DS.'persistance'.DS.'DAONumber.php');
require_once(JPATH_COMPONENT.DS.'domain'.DS.'DTONumber.php');

class DAONumberImpl implements DAONumber{
	
	public function addNumber($con, $dtoNumber){
		if(!$this->checkNumber($con, $dtoNumber->getIsoCode(), $dtoNumber->getNumber())){
			$data = new stdClass();
			$data->iso_code = $dtoNumber->getIsoCode();
			$data->number = $dtoNumber->getNumber();
			$data->spelling = $dtoNumber->getSpelling();
			$data->pronoun = $dtoNumber->getPronoun();
			$data->audio_path = $dtoNumber->getAudioPath();
			$data->active = $dtoNumber->isActive();

			if(!$con->insertObject( '#__hizkuntzak_numbers', $data)){
				echo $con->stderr();
				return false;
			}
			else 
				return true;	
		}
		else{
			
			return $this->updateNumber($con, $dtoNumber);
		}
		return false;
	}
	
	public function updateNumber($con, $dtoNumber){
		
		$sql = "UPDATE #__hizkuntzak_numbers SET spelling='$dtoNumber->spelling', ";
		$sql = $sql."pronoun='$dtoNumber->pronoun', audio_path='$dtoNumber->audioPath', ";
		$sql = $sql."active=$dtoNumber->active WHERE iso_code='$dtoNumber->iso_code' and number=$dtoNumber->number ";

		$con->setQuery($sql);
		
		if(!$con->query()){
			$con->stderr();
			return false;
		}
		else
			return true;
	}
	
	public function checkNumber($con, $lang_code, $number){
		$sql = "select * from #__hizkuntzak_numbers where (iso_code='$lang_code' AND number=$number)";
		
		$con->setQuery($sql);
		
    	$row = $con->loadObject();
    	
    	if($row == null || $row == ""){
    		return false;
    	}
    	return true;
	}
	
	public function getLangNumber($con, $lang_code, $active){
		$results = array();
		
		$sql = "SELECT #__hizkuntzak_numbers.* 
				FROM #__hizkuntzak_numbers 
				WHERE #__hizkuntzak_numbers.iso_code='$lang_code'";
		
		if($active){
			$sql = $sql. " AND #__hizkuntzak_numbers.active=1 ";
		}
		$sql = $sql. " ORDER BY #__hizkuntzak_numbers.number";

		$con->setQuery($sql);
		
    	$objectList = $con->loadObjectList();

        foreach($objectList as $row) {
        	
        	$number = new DTONumber();
        	
        	$number->setIsoCode($row->iso_code);
        	$number->setNumber($row->number);
        	$number->setSpelling($row->spelling);
        	$number->setPronoun($row->pronoun);
        	$number->setAudioPath($row->audio_path);
        	$number->setActive($row->active);
            
        	$results[] = $number;
          } 
		
		return $results;
	}
	
}